{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !wget https://f000.backblazeb2.com/file/malay-dataset/knowledge-graph/kelm/train_X\n",
    "# !wget https://f000.backblazeb2.com/file/malay-dataset/knowledge-graph/kelm/train_Y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'mesolitica-tpu.json'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tqdm import tqdm\n",
    "import re\n",
    "\n",
    "def cleaning(string):\n",
    "    string = string.replace('\\n', ' ').replace('\\t', ' ')\n",
    "    string = re.sub(r'[ ]+', ' ', string).strip()\n",
    "    return string"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import tensorflow_datasets as tfds\n",
    "from t5.data import preprocessors as prep\n",
    "import functools\n",
    "import t5\n",
    "import gin\n",
    "import sentencepiece as spm\n",
    "from glob import glob\n",
    "import os\n",
    "\n",
    "gin.parse_config_file('pretrained_models_base_operative_config.gin')\n",
    "vocab = 'sp10m.cased.ms-en.model'\n",
    "sp = spm.SentencePieceProcessor()\n",
    "sp.Load(vocab)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('train_X') as fopen:\n",
    "    train_X = fopen.read().split('\\n')\n",
    "    \n",
    "with open('train_Y') as fopen:\n",
    "    train_Y = fopen.read().split('\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 6032873/6032873 [02:26<00:00, 41280.67it/s]\n"
     ]
    }
   ],
   "source": [
    "with tf.io.gfile.GFile('knowledge-graph.tsv', \"w\") as outfile:\n",
    "    for i in tqdm(range(len(train_X))):\n",
    "        if len(train_X) and len(train_Y):\n",
    "            l = cleaning(train_X[i])\n",
    "            r = cleaning(train_Y[i])\n",
    "            outfile.write(\"%s\\t%s\\n\" % (l, r))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def knowledge_graph_dataset(split, shuffle_files = False):\n",
    "    del shuffle_files\n",
    "    ds = tf.data.TextLineDataset(\n",
    "        [\n",
    "            'knowledge-graph.tsv'\n",
    "        ]\n",
    "    )\n",
    "\n",
    "    ds = ds.map(\n",
    "        functools.partial(\n",
    "            tf.io.decode_csv,\n",
    "            record_defaults = ['', ''],\n",
    "            field_delim = '\\t',\n",
    "            use_quote_delim = False,\n",
    "        ),\n",
    "        num_parallel_calls = tf.data.experimental.AUTOTUNE,\n",
    "    )\n",
    "    ds = ds.map(lambda *ex: dict(zip(['question', 'answer'], ex)))\n",
    "    return ds\n",
    "\n",
    "def knowledge_graph_preprocessor(ds):\n",
    "    def to_inputs_and_targets(ex):\n",
    "        return {\n",
    "            'inputs': tf.strings.join(['grafik pengetahuan: ', ex['question']]),\n",
    "            'targets': ex['answer'],\n",
    "        }\n",
    "\n",
    "    return ds.map(\n",
    "        to_inputs_and_targets,\n",
    "        num_parallel_calls = tf.data.experimental.AUTOTUNE,\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "t5.data.TaskRegistry.remove('knowledge_graph_dataset')\n",
    "t5.data.TaskRegistry.add(\n",
    "    'knowledge_graph_dataset',\n",
    "    dataset_fn = knowledge_graph_dataset,\n",
    "    splits = ['train'],\n",
    "    text_preprocessor = [knowledge_graph_preprocessor],\n",
    "    sentencepiece_model_path = vocab,\n",
    "    metric_fns = [t5.evaluation.metrics.accuracy],\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "nq_task = t5.data.TaskRegistry.get(\"knowledge_graph_dataset\")\n",
    "ds = nq_task.get_dataset(split='knowledge-graph.tsv', sequence_length={\"inputs\": 1024, \"targets\": 1024})\n",
    "r = tfds.as_numpy(ds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'inputs_plaintext': b'grafik pengetahuan: Perkahwinan Figaro adalah episod Mad Men dari musim 1 dan diikuti oleh New Amsterdam.',\n",
       " 'inputs': array([12333,  5836,    31,   881,  2158,  3686,    47,    13,  2397,\n",
       "         1783,   162,    52,  5319,  3940,  1181,    42,   451,   179,\n",
       "           22,  5281,    60,   141, 14108,     3,     1]),\n",
       " 'targets_plaintext': b'Marriage of Figaro ( Mad Men ) season Mad Men ( season 1 ), part of the series Mad Men, followed by New Amsterdam ( Mad Men ).',\n",
       " 'targets': array([ 1366,   562,  1174,    18,    13,  2397,  1783,   162,    13,\n",
       "            4,  3940,  1181,    13,     5,  1015,  3940,  1181,    13,\n",
       "            4,  1015,   179,    13,     5,    14,   523,    18,    15,\n",
       "         1463,  3940,  1181,    14,  3093,    51,   141, 14108,    13,\n",
       "            4,  3940,  1181,    13,     5,     3,     1])}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "next(r)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from google.cloud import storage\n",
    "client = storage.Client()\n",
    "bucket = client.bucket('mesolitica-tpu-general')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "blob = bucket.blob('t5-data/knowledge-graph-train.tsv')\n",
    "blob.upload_from_filename('knowledge-graph.tsv')\n",
    "os.remove('knowledge-graph.tsv')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
